package com.chushouya.manager.service.admin.impl;

import com.chushouya.common.applet.WxClient;
import com.chushouya.common.config.WxOfficialConfig;
import com.chushouya.common.wx.dto.WxMessagePushRequest;
import com.chushouya.manager.dto.admin.clerk.*;
import com.general.framework.core.enums.DelFlagEnum;
import com.general.framework.core.lang.Beans;
import com.general.framework.core.lang.Dates;
import com.general.framework.core.lang.Jsons;
import com.general.framework.core.lang.Validate;
import com.general.framework.core.schema.PageResult;
import com.chushouya.manager.constants.ClerkStatusEnum;
import com.chushouya.manager.constants.ClerkUserTypeEnum;
import com.chushouya.manager.constants.ClerkWorkStatusEnum;
import com.chushouya.manager.dao.entity.ClerkEntity;
import com.chushouya.manager.dao.entity.UserEntity;
import com.chushouya.manager.dao.entity.UserExtendEntity;
import com.chushouya.manager.dao.repository.ClerkRepository;
import com.chushouya.manager.dao.repository.UserExtendRepository;
import com.chushouya.manager.dao.repository.UserRepository;
//=====manager.dto.admin.clerk.*;
import com.chushouya.manager.dto.admin.clerk.*;
import com.chushouya.manager.service.admin.ClerkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Service
public class ClerkServiceImpl implements ClerkService {

    @Resource
    private ClerkRepository clerkRepository;

    @Resource
    private WxOfficialConfig wxOfficialConfig;
    @Resource
    private UserExtendRepository userExtendRepository;

    @Resource
    private UserRepository userRepository;


    @Override
    public PageResult<ClerkListDTO> selectPage(ClerkQuery query) {
        final PageResult<ClerkEntity> pageResult = clerkRepository.selectPageResult(query);
        return PageResult.of(pageResult,ClerkListDTO.class);
    }

    @Override
    public ClerkDetailDTO detail(Long id) {
        ClerkEntity clerkEntity = selectByPrimaryKey(id);
        ClerkDetailDTO clerkDetailDTO = Beans.copy(clerkEntity, ClerkDetailDTO.class);
        clerkDetailDTO.setArea(Jsons.parseArray(clerkEntity.getArea(), String.class));
        clerkDetailDTO.setAreaCode(Jsons.parseArray(clerkEntity.getAreaCode(), String.class));
        clerkDetailDTO.setUserTypeText(ClerkUserTypeEnum.getDesc(clerkEntity.getUserType()));
        return clerkDetailDTO;
    }

    private ClerkEntity selectByPrimaryKey(Long id) {
        Validate.isNull(id, "id不能为空");
        ClerkEntity clerkEntity = clerkRepository.selectByPrimaryKey(id);
        Validate.isNull(clerkEntity, "业务员不存在");
        return clerkEntity;
    }

    @Override
    public void save(ClerkSaveDTO dto) {
        ClerkEntity clerkEntity = Beans.copy(dto, ClerkEntity.class);
        clerkEntity.setPayPartnerId(Jsons.toJSONString(dto.getPayPartnerIdList()));

        clerkRepository.insertSelective(clerkEntity);
    }

    @Override
    public void remove(Long id) {
        Validate.isNull(id, "id不能为空");
        ClerkEntity update = new ClerkEntity();
        update.setClerkId(id);
        update.setDelFlag(DelFlagEnum.delete.getValue());
        update.setUpdateTime(Dates.getTimeNow());
        clerkRepository.updateByPrimaryKeySelective(update);
    }

    @Override
    public void update(ClerkUpdateDTO dto) {
//        Validate.isTrue(Lists.isEmpty(dto.getArea()), "请选择服务区域");
        ClerkEntity clerkEntity = selectByPrimaryKey(dto.getClerkId());

        boolean syncUserInfo = (!Objects.equals(clerkEntity.getClerkPhone(), dto.getClerkPhone()))
                || (!Objects.equals(clerkEntity.getClerkName(), dto.getClerkName()));
                Beans.copyProperties(dto, clerkEntity);

//        clerkEntity.setArea(Jsons.toJSONString(dto.getArea()));
//        clerkEntity.setAreaCode(Jsons.toJSONString(dto.getAreaCode()));
        clerkEntity.setPayPartnerId(Jsons.toJSONString(dto.getPayPartnerIdList()));
        clerkRepository.updateByPrimaryKeySelective(clerkEntity);

        if (syncUserInfo) {
            UserEntity updateUser = new UserEntity();
            updateUser.setUserId(clerkEntity.getUserId());
            updateUser.setUserName(clerkEntity.getClerkName());
            updateUser.setUserPhone(clerkEntity.getClerkPhone());
            updateUser.setUpdateTime(Dates.getTimeNow());
            userRepository.updateByPrimaryKeySelective(updateUser);
        }
    }


    @Override
    public void editStatus(Long clerkId, Integer status) {
        ClerkEntity update = new ClerkEntity();
        update.setClerkId(clerkId);
        update.setStatus(status);
        update.setUpdateTime(Dates.getTimeNow());
        clerkRepository.updateByPrimaryKeySelective(update);

    }

    @Override
    public void editWorkStatus(Long clerkId, Integer workStatus) {
        Validate.isNull(clerkId, "业务员id不能为空");
        Validate.isNull(workStatus, "上班状态不能为空");

        ClerkEntity update = new ClerkEntity();
        update.setClerkId(clerkId);
        update.setWorkStatus(workStatus);
        update.setUpdateTime(Dates.getTimeNow());
        clerkRepository.updateByPrimaryKeySelective(update);
    }

    @Override
    public void audit(Long clerkId) {
        ClerkEntity update = new ClerkEntity();
        update.setClerkId(clerkId);
        update.setStatus(ClerkStatusEnum.enable.value());
        update.setWorkStatus(ClerkWorkStatusEnum.working.value());
        update.setUpdateTime(Dates.getTimeNow());
        clerkRepository.updateByPrimaryKeySelective(update);

        try {
            final ClerkEntity clerkEntity = clerkRepository.selectByPrimaryKey(clerkId);
            log.info("推送业务员申请已通过审核微信通知,{}", wxOfficialConfig);
            UserExtendEntity userExtendEntity = userExtendRepository.selectByAppIdAndUserId(wxOfficialConfig.getAppId(), clerkEntity.getUserId());
            //发送微信模板消息
            WxMessagePushRequest message = new WxMessagePushRequest();
            message.setTemplateId("z4M6NK97Mz-MdU-4YdrmrYDjm3bnp1P_sDQOsOMuCR4");
            message.setOpenId(userExtendEntity.getOpenId());
            Map<String, WxMessagePushRequest.Value> data = new HashMap<>();
            data.put("thing1", new WxMessagePushRequest.Value(clerkEntity.getClerkName()));
            data.put("time2", new WxMessagePushRequest.Value(Dates.getDateNowStr()));
            message.setData(data);
            new WxClient(wxOfficialConfig.getAppId(), wxOfficialConfig.getAppSecret()).sendOfficialTemplateMessage(message);
        } catch (Exception e) {
            log.info("推送业务员申请已通过审核微信通知失败,{}", e.getMessage());
        }
    }
}
